package dept_service

import (
	"gorm.io/gorm"
	dd "pear-admin-layui-go/app/sys/dept/domain"
	fd "pear-admin-layui-go/framework/database"
)

func Tree() []dd.Dept {
	var depts []dd.Dept
	fd.Db.Select("id", "pid", "name").Where("del_flag = false").Find(&depts)
	return depts
}

func Edit(der *dd.DeptEditRequest) *gorm.DB {
	return fd.Db.Model(&dd.Dept{Id: der.Id}).Select("name", "location", "remark", "update_time", "update_by",
		"update_name").Updates(dd.Dept{
		Name:       der.Name,
		Location:   der.Location,
		Remark:     der.Remark,
		UpdateTime: der.UpdateTime,
		UpdateBy:   der.UpdateBy,
		UpdateName: der.UpdateName,
	})
}

func EditPage(id int64) *dd.Dept {
	var dept = dd.Dept{
		Id: id,
	}
	fd.Db.Select("name", "location", "remark").First(&dept)
	return &dept
}

func Save(dsr *dd.DeptSaveRequest) (*dd.Dept, *gorm.DB) {
	var dept = dd.Dept{
		Pid:        dsr.Pid,
		Name:       dsr.Name,
		Location:   dsr.Location,
		Remark:     dsr.Remark,
		CreateTime: dsr.CreateTime,
		CreateBy:   dsr.CreateBy,
		CreateName: dsr.CreateName,
	}
	return &dept, fd.Db.Create(&dept)
}

func Table(dtr *dd.DeptTableRequest) ([]dd.Dept, int64) {
	var count int64
	db := fd.Db.Model(&dd.Dept{}).Where("del_flag = false").Select("id", "pid", "name", "location",
		"leader", "leader_name", "remark", "create_time", "create_name", "update_time", "update_name")
	if dtr.Name != "" {
		db.Where("name like ?", "%"+dtr.Name+"%")
	}
	db.Count(&count)
	if count == 0 {
		return []dd.Dept{}, count
	}
	var depts []dd.Dept
	db.Limit(dtr.Limit).Offset((dtr.Page - 1) * dtr.Limit).Find(&depts)
	return depts, count
}
